<?php

class MiniUrl {
    private  $config;
    function __construct($config = []){
        $this->config = $config;
    }
    
    function urlGenerate($path, $code)
    {
        $url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=" . $this->config['app_id'] . '&secret=' . $this->config['secret'];
        $result = $this->getData($url);
        $token  = $result['access_token'];
        $params = [
            "path"  => $path,
            "query" => "code=" . $code,
            "is_expire"   => false,
            "expire_type"   => 1,
            "expire_time" => 1606737600
        ];
        $url    = "https://api.weixin.qq.com/wxa/generate_urllink?access_token=" . $token;
        $result = $this->getData($url, $params, true);
        echo json_encode($result);
        return;
    }
    
    function getData($url, $params = false, $ispost = 0, $header = [], $https = 0)
    {
        $httpInfo = array();
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_1_1);
        curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 30);
        curl_setopt($ch, CURLOPT_TIMEOUT, 30);
        if ($header) {
            $newHeader = [];
            foreach ($header as $k => $v) {
                $newHeader[] = $k . ':' . $v;
            }
            curl_setopt($ch, CURLOPT_HTTPHEADER, $newHeader);
        }

        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        if ($https) {
            curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE); // 对认证证书来源的检查
            curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, FALSE); // 从证书中检查SSL加密算法是否存在
        }
        if ($ispost) {
            curl_setopt($ch, CURLOPT_POST, true);
            curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($params));
            curl_setopt($ch, CURLOPT_URL, $url);
        } else {
            if ($params) {
                if (is_array($params)) {
                    $params = http_build_query($params);
                }
                curl_setopt($ch, CURLOPT_URL, $url . '?' . $params);
            } else {
                curl_setopt($ch, CURLOPT_URL, $url);
            }
        }

        $response = curl_exec($ch);

        $error = curl_error($ch);

        if ($response === FALSE  || $error) {
            return false;
        }
        curl_close($ch);
        $result = json_decode($response, true) ? json_decode($response, true) : $response;
        return $result;
    }
}

 $config = [
    'app_id' => 'wxc6c5d7ec1a015215', //小程序app_id
    'secret' => 'b41e22fe8d7546b9ab7f1f465b14d7be', //小程序的secret
 ];
 $code = $_GET['code'];
 $path = $_GET['path'];
(new  MiniUrl($config))->urlGenerate($path, $code);